package com.example.blue;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.UUID;

public class BindActivity extends AppCompatActivity {

    private static final String TAG = "BindActivity";
    private TextView tvDeviceInfo;
    private Button magButton, tuoButton, testButton,oulaButton;

    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isServiceBound = false;

    // 定义连接服务的 ServiceConnection
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isServiceBound = true;
            // 可以进行一些初始化操作，例如设置UI状态
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBound = false;
        }
    };
    private final BroadcastReceiver bleReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothService.ACTION_CONNECTED.equals(action)) {
                Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();
            } else if (BluetoothService.ACTION_DISCONNECTED.equals(action)) {
                Toast.makeText(context, "蓝牙已断开", Toast.LENGTH_SHORT).show();
            } else if (BluetoothService.ACTION_DATA_AVAILABLE.equals(action)) {
                Toast.makeText(context, "蓝牙收到数据", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("连接设备");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(BindActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }
        // 初始化视图
        initViews();
        // 获取从主活动传递的设备信息
        Intent serviceIntent = new Intent(this, BluetoothService.class);
        serviceIntent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        startService(serviceIntent); // 确保服务在后台运行
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

        // 显示设备信息
        tvDeviceInfo.setText(deviceId);
        // 设置按钮点击监听器
        magButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent magInt = new Intent(BindActivity.this, MagCorActivity.class);
                startActivity(magInt);

            }
        });

        tuoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BindActivity.this, TuoCorActivity.class);
                startActivity(intent);
            }
        });

        testButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BindActivity.this, TestActivity.class);
                startActivity(intent);
            }
        });
        oulaButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BindActivity.this, OulajiaoActivity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothService.ACTION_CONNECTED);
        filter.addAction(BluetoothService.ACTION_DISCONNECTED);
        filter.addAction(BluetoothService.ACTION_DATA_AVAILABLE);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // API 33+
            registerReceiver(bleReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(bleReceiver, filter);
        }
    }

    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initViews() {
        tvDeviceInfo = findViewById(R.id.tvDeviceInfo);
        magButton = findViewById(R.id.magCorrect);
        tuoButton = findViewById(R.id.tuoluoCorrect);
        testButton = findViewById(R.id.funTest);
        oulaButton = findViewById(R.id.oulajiao);
        magButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
        tuoButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
        testButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
        oulaButton.setBackgroundColor(Color.parseColor("#1E90FF")); // 使用十六进制颜色值
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "需要权限: " + permissions[i], Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}